import axios from "axios";
import router from "@/router";

import { isSuccessResult, isUnAuthResult } from "./utils.ts";
import { handleAjaxError, ApiError } from "./error-handler.ts";

import { LOGIN_ROUTE_NAME } from "@/router/routes/login.route.ts";

import type { ApiResult } from "./model";


export const http = axios.create({
    baseURL: import.meta.env.APP_API_PREFIX,
});

http.interceptors.request.use(config => {
    return config;
}, reason => {
    handleAjaxError(reason);
    throw reason;
});

http.interceptors.response.use(response => {
    // 响应结果校验
    const data = response.data as ApiResult<any>
    if (!data) {
        throw new Error("Incomplete response data");
    }
    // 响应code校验
    if (!isSuccessResult(data.code)) {
        if (isUnAuthResult(data.code)) {
            router.push({ name: LOGIN_ROUTE_NAME });
        }
        throw handleAjaxError(new ApiError(data.code, data.msg));
    }
    /*
        最终的返回结果是响应体的真正内容, 例如:
        {
            code
            msg
            data: value
        }
        那么返回的就是value
     */
    return data.data;
}, reason => {
    handleAjaxError(reason);
    throw reason;
});